package com.suray.wcs.service.core.util;

import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

/**
 * @author shaozn
 * @date 2019/12/19 - 12:58
 * @Description TODO
 */
public class HttpClientSpring {

    /**
     * 向目的URL发送post请求
     *
     * @param url        目的url
     * @param jsonParams 发送的参数
     * @return AdToutiaoJsonTokenData
     */
    public static String sendPostRequest(String url, String jsonParams) {
        RestTemplate client     = new RestTemplate();
        //新建Http头，add方法可以添加参数
        HttpHeaders headers = new HttpHeaders();
        //设置请求发送方式
        HttpMethod method = HttpMethod.POST;
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        //将请求头部和参数合成一个请求
        HttpEntity<String> requestEntity = new HttpEntity<String>(jsonParams, headers);
        //执行HTTP请求，将返回的结构使用String 类格式化（可设置为对应返回值格式的类）
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);

        return response.getBody();
    }

    /**
     * 向目的URL发送get请求
     *
     * @param url        目的url
     * @param jsonParams 发送的参数
     * @return AdToutiaoJsonTokenData
     */
    public static String sendGetRequest(String url, String jsonParams) {
        RestTemplate client = new RestTemplate();
        //新建Http头，add方法可以添加参数
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.GET;
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        //将请求头部和参数合成一个请求
        HttpEntity<String> requestEntity = new HttpEntity<String>(jsonParams, headers);
        //执行HTTP请求，将返回的结构使用String 类格式化
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);

        return response.getBody();
    }
}